package cn.com.taiji.oospub.wechat.scheduler;

import cn.com.taiji.oospub.wechat.common.helper.DataBaseInfo;
import cn.com.taiji.oospub.wechat.common.tool.TimeTools;
import cn.com.taiji.oospub.wechat.entity.*;
import cn.com.taiji.oospub.wechat.service.ICoursesOrdersDetailsService;
import cn.com.taiji.oospub.wechat.service.ICoursesOrdersService;
import cn.com.taiji.oospub.wechat.service.ICoursesService;
import cn.com.taiji.oospub.wechat.service.IOrderOfDaynutService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.dreamyoung.mprelation.AutoMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.List;

import static cn.com.taiji.oospub.wechat.entity.CoursesOrders.CoursesOrderStatus.*;

@Component
@PropertySource("classpath:config/scheduler.properties")
public class OrdersScheduler {


    private static final Logger logger = LoggerFactory.getLogger(CourseScheduler.class);


    @Value("${kongxc_Diancan_Ip}")
    private String kongxc_Diancan_Ip;
    @Value("${kongxc_Diancan_oosPort}")
    private String kongxc_Diancan_oosPort;
    @Value("${kongxc_Diancan_oosSid}")
    private String kongxc_Diancan_oosSid;
    @Value("${kongxc_Diancan_oosUser}")
    private String kongxc_Diancan_oosUser;
    @Value("${kongxc_Diancan_oosPw}")
    private String kongxc_Diancan_oosPw;


    @Autowired
    private ICoursesOrdersDetailsService coursesOrdersDetailsService;
    @Autowired
    private ICoursesOrdersService coursesOrdersService;
    @Autowired
    private ICoursesService coursesService;
    @Autowired
    private IOrderOfDaynutService orderOfDaynutService;
    @Autowired
    private AutoMapper autoMapper;


    // <!-- 删除每日顾客未下的订单主单，因为第二天不售此餐 -->
    @Scheduled(cron = "0 45 23 * * ?")
    public void deleteEveryDayInvalidOrder() {
        // TODO Auto-generated method stub
        String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        DataBaseInfo info = new DataBaseInfo(kongxc_Diancan_Ip, kongxc_Diancan_oosPort, kongxc_Diancan_oosSid, kongxc_Diancan_oosUser, kongxc_Diancan_oosPw, driver);

        String url = "jdbc:sqlserver://" + info.getDbIp() + ":" + info.getDbPort() + ";databaseName=" + info.getDbSid();
        String user = info.getDbUser(), password = info.getDbPw();
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            logger.info("驱动加载失败");
        }
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
            if (connection != null) {
                logger.info("连接成功 : " + connection);
            }
            String sql = "DELETE from Courses_orders where id_delete = ? ";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, "1");
            preparedStatement.executeUpdate();
            connection.commit();
        } catch (SQLException e) {
            logger.error("Connection is invalid!");
            e.printStackTrace();
        } finally {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //<!-- 删除每日顾客未下的订单详情，因为第二天不售此餐 -->
    @Scheduled(cron = "0 59 23 * * ?")
    public void deleteEveryDayInvalidDetail() {
        // TODO Auto-generated method stub
        String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        DataBaseInfo info = new DataBaseInfo(kongxc_Diancan_Ip, kongxc_Diancan_oosPort, kongxc_Diancan_oosSid, kongxc_Diancan_oosUser, kongxc_Diancan_oosPw, driver);

        String url = "jdbc:sqlserver://" + info.getDbIp() + ":" + info.getDbPort() + ";databaseName=" + info.getDbSid();
        String user = info.getDbUser(), password = info.getDbPw();
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            logger.info("驱动加载失败");
        }
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
            if (connection != null) {
                logger.info("连接成功 : " + connection);
            }
            String sql = "DELETE from Courses_orders_details where is_effective= ? ";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, "0");
            preparedStatement.executeUpdate();
            connection.commit();
        } catch (SQLException e) {
            logger.error("Connection is invalid!");
            e.printStackTrace();
        } finally {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    //   <!-- 同步pos订单,向 orderOfDaynut插入数据-->
//    @Scheduled(cron = "0 37 23 * * ?")
//    @Scheduled(cron = "0 0/1 * * * ? ")
    public void addHistory() {
        System.out.println("开始同步订单数据");
        String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        DataBaseInfo info = new DataBaseInfo(kongxc_Diancan_Ip, kongxc_Diancan_oosPort, kongxc_Diancan_oosSid, kongxc_Diancan_oosUser, kongxc_Diancan_oosPw, driver);
        String url = "jdbc:sqlserver://" + info.getDbIp() + ":" + info.getDbPort() + ";databaseName=" + info.getDbSid();
        String user = info.getDbUser(), password = info.getDbPw();
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            logger.info("驱动加载失败");
        }
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
            if (connection != null) {
                logger.info("连接成功 : " + connection);
            }
            String sql = "select id , school_id, pay_time from Courses_orders where "
                    + "(status = ? or status = ? or status = ? or status = ?) "
                    + "and (pay_way =? or pay_way =? or pay_way =? ) and pay_time > ? and pay_time < ? ";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, "YZF");
            preparedStatement.setString(2, "BCZ");
            preparedStatement.setString(3, "BCWC");
            preparedStatement.setString(4, "DDYWC");
            preparedStatement.setString(5, "WX");
            preparedStatement.setString(6, "HTZ");
            preparedStatement.setString(7, "CK");
            preparedStatement.setTimestamp(8, new Timestamp(TimeTools.startOfDay(Calendar.getInstance()).getTime().getTime()));
            preparedStatement.setTimestamp(9, new Timestamp(TimeTools.endOfDay(Calendar.getInstance()).getTime().getTime()));
            resultSet = preparedStatement.executeQuery();
            CoursesOrders coursesOrders;

            while (resultSet.next()) {
                OrderOfDaynut orderOfDaynut = new OrderOfDaynut();
                coursesOrders = coursesOrdersService.getById(resultSet.getString(1));
                List<CoursesOrdersDetails> ordersDetailsList = coursesOrdersDetailsService.findByProperty("order_id", coursesOrders.getId());
                if (ordersDetailsList.size() <= 0) {
                    continue;
                }
                CoursesOrdersDetails coursesOrdersDetails = ordersDetailsList.get(0);
                MemberBaseInfo memberBaseInfo = autoMapper.mapperEntity(coursesOrdersDetails.getCreatorInfo());
                orderOfDaynut.setMemberId(coursesOrders.getMemberId());
                orderOfDaynut.setIdNumber(memberBaseInfo.getIdNumber());
                orderOfDaynut.setSchoolId(memberBaseInfo.getSchoolId());
                orderOfDaynut.setSchoolCode(memberBaseInfo.getSchool().getCode());
                Courses courses = coursesService.getById(coursesOrdersDetails.getCourseId());
                if (courses != null) {
                    orderOfDaynut.setResourseId(courses.getId());
                    orderOfDaynut.setResourseCode(courses.getPosNo());
                    orderOfDaynut.setResourseName(courses.getNameCh());
                    orderOfDaynut.setResourseNameEn(courses.getNameEn());
                }
                orderOfDaynut.setQuantity(coursesOrdersDetails.getQuantity());
                orderOfDaynut.setMealCode(coursesOrdersDetails.getMealCode());
                orderOfDaynut.setMealName(coursesOrdersDetails.getMealName());
                orderOfDaynut.setConTime(autoMapper.mapperEntity(coursesOrdersDetails).getMainOrder().getPayTime());
                orderOfDaynut.setCreateTime(LocalDateTime.now());
                orderOfDaynutService.save(orderOfDaynut);
            }
            System.out.println("订单同步完成");
        } catch (SQLException e) {
            logger.error("Connection is invalid!");
            e.printStackTrace();
        } finally {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 更新第二天订单状态以及停用菜品
     */
    @Scheduled(cron = "${stopTomorrow}")
    public void stopTomorrow() {
        //更新订单
        coursesOrdersService.updateOrderStatus(null, LocalDate.now().plusDays(1), YZF, BCZ);
        //停用菜品
        coursesService.clearCourses(null, LocalDate.now().plusDays(1));
    }

    /**
     * 更新早餐订单以及停用菜品
     */
    @Scheduled(cron = "${stopTomorrowBreakfast}")
    public void stopTomorrowBreakfast() {
        //更新订单
        coursesOrdersService.updateOrderStatus("01", LocalDate.now(), YZF, BCZ);
        //停用菜品
        coursesService.clearCourses("01", LocalDate.now());
    }

    /**
     * 更新早餐订单以及停用菜品
     */
    @Scheduled(cron = "${stopBreakfast}")
    public void stopBreakfast() {
        //更新订单
        coursesOrdersService.updateOrderStatus("01", LocalDate.now(), YZF, BCZ);
        //停用菜品
        coursesService.clearCourses("01", LocalDate.now());
    }

    /**
     * 更新午餐订单以及停用菜品
     */
    @Scheduled(cron = "${stopLunch}")
    public void stopLunch() {
        //更新订单
        coursesOrdersService.updateOrderStatus("02", LocalDate.now(), YZF, BCZ);
        //停用菜品
        coursesService.clearCourses("01", LocalDate.now());
    }

    /**
     * 更新晚餐订单以及停用菜品
     */
    @Scheduled(cron = "${stopDinner}")
    public void stopDinner() {
        //更新订单
        coursesOrdersService.updateOrderStatus("03", LocalDate.now(), YZF, BCZ);
        //停用菜品
        coursesService.clearCourses("01", LocalDate.now());
    }


    /**
     * 更新订单
     */
    @Scheduled(cron = "0 30 23 * * ?")
    public void update() {
        UpdateWrapper<CoursesOrders> coursesOrdersUpdateWrapper = new UpdateWrapper<>();
        coursesOrdersUpdateWrapper.eq("status", BCZ);
        coursesOrdersUpdateWrapper.le("take_time", LocalDateTime.of(LocalDate.now(), LocalTime.MAX));
        coursesOrdersUpdateWrapper.set("status", DDYWC);
        coursesOrdersUpdateWrapper.set("completed_time", LocalDateTime.now());
        coursesOrdersService.update(coursesOrdersUpdateWrapper);
    }


}
